package com.ruoyi.business.mq;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.business.domain.User;
import com.ruoyi.business.domain.dto.HardwareDataReceptionDTO;
import com.ruoyi.business.service.IScoreService;
import com.ruoyi.business.service.IUserService;
import io.swagger.util.Json;
import org.eclipse.paho.client.mqttv3.*;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class MqttConsumer {

    @Value("${mqtt.broker}")
    private String broker;

    @Value("${mqtt.clientId}")
    private String clientId;

    @Value("${mqtt.topic}")
    private String topic;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    private MqttClient client;

    @Autowired
    private IScoreService scoreService;

    @Autowired
    private IUserService userService;

    @PostConstruct
    public void init() {
        try {
            // 1. 初始化客户端
            client = new MqttClient(broker, clientId, new MemoryPersistence());

            // 2. 配置连接参数
            MqttConnectOptions options = new MqttConnectOptions();
            options.setCleanSession(true);
            options.setUserName(username);
            options.setPassword(password.toCharArray());
            options.setConnectionTimeout(10);
            options.setKeepAliveInterval(20);

            // 3. 设置消息到达回调
            client.setCallback(new MqttCallbackExtended() {
                @Override
                public void connectComplete(boolean reconnect, String serverURI) {
                    System.out.println("Connected to broker: " + serverURI);
                }

                @Override
                public void messageArrived(String topic, MqttMessage message) {
                    System.out.printf("Received [%s]: %s%n", topic, new String(message.getPayload()));
                    try{
                        String str = new String(message.getPayload());
                        HardwareDataReceptionDTO dto = JSON.parseObject(str, HardwareDataReceptionDTO.class);
                        scoreService.addScore(dto);
                    }catch (Exception e){
                        System.out.println("接收数据异常");
                    }
                }

                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {}

                @Override
                public void connectionLost(Throwable cause) {
                    System.err.println("Connection lost: " + cause.getMessage());
                }
            });

            // 4. 建立连接并订阅主题
            client.connect(options);
            client.subscribe(topic, 1); // QoS级别1

        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    public void destroy() throws MqttException {
        if (client != null && client.isConnected()) {
            client.disconnect();
            client.close();
        }
    }
}